/*
 * @Author: Yang Zhang
 * @Date: 2021-11-18 22:14:14
 * @LastEditors: Yang Zhang
 * @LastEditTime: 2021-11-18 22:14:15
 * @Description: 工具包
 */
import { request } from './request'

const deepClone = (source: any, dest?: any) => {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments')
  }
  dest = dest || (source.constructor === Array ? [] : {})
  for (const key in source) {
    if (source.hasOwnProperty(key)) {
      if (source[key] && typeof source[key] === 'object') {
        dest[key] = source[key].constructor === Array ? [] : {}
        deepClone(source[key], dest[key])
      } else {
        dest[key] = source[key]
      }
    }
  }
  return dest
}

//  读取localStorage
function setStorageItem(key: any, val: any): void {
  window.localStorage.setItem(key, JSON.stringify(val))
}

//  读取localStorage
function getStorageItem(key: any): any {
  const val: any = window.localStorage.getItem(key)
  return JSON.parse(val)
}
//  删除
function removeStoreItem(key: any): void {
  window.localStorage.removeItem(key)
}

//  获取localstorage token
function getToken() {
  return getStorageItem('token')
}

//  禁止中文输入
const stopChinese = (val: any) => {
  return val.replace(/[\u4E00-\u9FA5]/gi, '')
}

//  下载文件    type--true 打开新空白页面下载
const downloadFile = (url: string, type: any) => {
  if (!type) {
    window.open(url)
  } else {
    const downloadWin: any = window.open()
    downloadWin.location = url
  }
}

//  浏览器全屏
const fullScreen = () => {
  const el: any = document.documentElement

  const rfs =
    el.requestFullScreen ||
    el.webkitRequestFullScreen ||
    el.mozRequestFullScreen ||
    el.msRequestFullScreen

  if (typeof rfs !== 'undefined' && rfs) {
    rfs.call(el)
  }
}

const cancelFullScreen = () => {
  if ((document as any).webkitCancelFullScreen) {
    ; (document as any).webkitCancelFullScreen()
  } else if ((document as any).mozCancelFullScreen) {
    ; (document as any).mozCancelFullScreen()
  } else if ((document as any).exitFullscreen) {
    ; (document as any).exitFullscreen()
  } else if ((document as any).msExitFullscreen) {
    ; (document as any).msExitFullscreen()
  }
}

//  事件绑定兼容
const addHandle = (dom: any, type: string, fn: Function) => {
  if ((document as any).addEventListener) {
    dom.addEventListener(type, fn, false)
  } else if ((document as any).attachEvent) {
    dom.attachEvent('on' + type, fn)
  } else {
    const oldDomFun = dom['on' + type]
    dom['on' + type] = () => {
      oldDomFun()
      fn && fn()
    }
  }
}

//  事件解绑
const removeHandle = (dom: any, type: string, fn: Function) => {
  if ((document as any).removeEventListener) {
    dom.removeEventListener(type, fn)
  } else if ((document as any).detachEvent) {
    dom.detachEvent('on' + type, fn)
  } else {
    dom['on' + type] = null
  }
}

//  防抖
const debounce = (fn: Function, delay: number) => {
  let timer: any
  return (...args: any) => {
    if (timer) {
      clearTimeout(timer)
      timer = null
    }
    // 使用箭头函数来处理this问题
    timer = setTimeout(() => fn(args), delay)
  }
}

const delayHandle = (delay: number) => {
  return new Promise<void>((resolve) => {
    setTimeout(() => {
      resolve()
    }, delay)
  })
}

//  延迟获取数据
const delayGetData = (delay: number, data: any) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(data)
    }, delay)
  })
}

//   || (styles.OLink === '' && ['', 'o'])
const getBrowserPrefix = () => {
  const styles = window.getComputedStyle(document.documentElement, '')

  const res = Array.prototype.slice
    .call(styles)
    .join('')
    .match(/-(moz|webkit|ms)-/)

  // eslint-disable-next-line valid-typeof
  if (typeof res === 'boolean' || typeof res === null) {
    return false
  } else {
    return (res && res[1]) || ''
  }
}

const getRandom = (num: number) => {
  return -Math.floor(Math.random() * num)
}

//  图片等比适配缩放适配容器
const getImgSize = (
  maxWidth: number,
  maxHeight: number,
  imgWidth: number,
  imgHeight: number,
  type: null | string
) => {
  const scale = maxWidth / maxHeight
  const imgScale = imgWidth / imgHeight
  let width
  let height

  if (type) {
    if (imgScale >= scale) {
      height = maxHeight
      width = height * imgScale
    } else {
      width = maxWidth
      height = width * (imgHeight / imgWidth)
    }
  } else {
    if (imgScale >= scale) {
      width = maxWidth
      height = width * (imgHeight / imgWidth)
    } else {
      height = maxHeight
      width = height * imgScale
    }
  }

  return {
    width,
    height
  }
}

// 设置标签颜色
const setTagColor = (list: any[], color: string) => {
  list.forEach((item: any) => {
    item.color = color
  })
}

// 设置tree checkbox是否禁用
const setTreeCheckboxIsDisabled = (
  list: any[],
  matchKey: string,
  key: string,
  allIsDisabled = false
) => {
  if (list.length) {
    list[0].disabled = allIsDisabled
    const children = list[0].children
    const noGroup: any = children
      ? children.find((item: any) => item[matchKey] === key)
      : list.find((item: any) => item[matchKey] === key)

    if (noGroup) {
      noGroup.disabled = true
    }

    return list
  }
}

export {
  deepClone,
  setStorageItem,
  getStorageItem,
  removeStoreItem,
  downloadFile,
  stopChinese,
  request,
  getToken,
  fullScreen,
  cancelFullScreen,
  addHandle,
  removeHandle,
  debounce,
  delayHandle,
  getBrowserPrefix,
  getRandom,
  getImgSize,
  delayGetData,
  setTagColor,
  setTreeCheckboxIsDisabled
}
